/**
 * 系统设置状态管理（全域配置）
 */
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import { i18n, Language } from '@/utils/i18n'

export interface SystemSettings {
  branding: {
    platformName: string
    platformNameZh: string
    platformNameEn: string
    platformLogo: string
    slogan: string
    copyright: string
    icpNumber: string
    enableMultiLanguage: boolean
    defaultLanguage: string
    supportedLanguages: string[]
    enableMultiTimezone: boolean
    timezone: string
    supportedTimezones: string[]
    customerServicePhone: string
    customerServiceIM: string
    customerServiceEmail: string
  }
  business: {
    transaction: {
      paymentChannels: {
        alipay: boolean
        wechat: boolean
        bank: boolean
        cod: boolean
      }
      withdrawalCycle: 'T+1' | 'T+3' | 'T+7'
      withdrawalFeeRate: number
      couponStackable: boolean
    }
    product: {
      customCategories: string[]
      skuGenerationRule: 'color-size' | 'attribute-combination' | 'custom'
      inventoryWarningEnabled: boolean
      inventoryWarningThreshold: number
    }
    marketing: {
      membershipLevels: Array<{
        id: string
        name: string
        threshold: number
        perks: string
      }>
      enableGroupPurchase: boolean
      enablePreSale: boolean
      categoryLimitedTools: Array<{
        category: string
        feature: string
        enabled: boolean
      }>
      promotionTemplates: Array<{
        id: string
        name: string
        rule: string
        scope: string
      }>
    }
  }
  permissions: {
    rbacEnabled: boolean
    roles: Array<{
      key: string
      name: string
      description: string
      permissions: string[]
      restrictedActions?: string[]
    }>
  }
  integrations: {
    oauthProviders: {
      wechat: { enabled: boolean; appId: string; appSecret: string; callback: string }
      qq: { enabled: boolean; appId: string; appSecret: string; callback: string }
      alipay: { enabled: boolean; appId: string; appSecret: string; callback: string }
    }
    erp: { enabled: boolean; vendor: string; appKey: string; secret: string; callbackUrl: string }
    wms: { enabled: boolean; vendor: string; appKey: string; secret: string; callbackUrl: string }
    crm: { enabled: boolean; vendor: string; appKey: string; secret: string; callbackUrl: string }
    logistics: Array<{
      provider: string
      enabled: boolean
      apiKey: string
      template: string
    }>
  }
  technical: {
    caching: {
      enabled: boolean
      redisTtlMinutes: number
      cacheWarmUp: boolean
    }
    logging: {
      retentionDays: number
      auditRetentionDays: number
      sensitiveDataMasking: boolean
    }
    api: {
      defaultTimeoutSeconds: number
      orderTimeoutSeconds: number
      enableCircuitBreaker: boolean
    }
    backup: {
      enabled: boolean
      scheduleCron: string
      offsiteEnabled: boolean
      lastBackupAt?: string
    }
  }
  advanced: {
    sandboxMode: {
      enabled: boolean
      guide: string
      testers: string[]
    }
    multiTenant: {
      enabled: boolean
      tenantRules: Array<{
        tenant: string
        enabledFeatures: string[]
        lockedSettings: string[]
      }>
    }
    smartRecommendations: {
      enabled: boolean
      industry: string
      recommendedCombos: Array<{
        name: string
        description: string
        applyToCategories: string[]
      }>
    }
    versioning: {
      autoSnapshot: boolean
      versions: Array<{
        id: string
        label: string
        createdAt: string
        author: string
        description: string
      }>
    }
  }
}

interface SystemSettingsState {
  settings: SystemSettings
  updateSettings: (settings: Partial<SystemSettings>) => void
  resetSettings: () => void
}

const createDefaultSettings = (locale: Language = i18n.getLocale() as Language): SystemSettings => ({
  branding: {
    platformName: '电商后台管理系统',
    platformNameZh: '电商后台管理系统',
    platformNameEn: 'E-commerce Admin Console',
    platformLogo: '',
    slogan: '连接商家与消费者的全链路运营平台',
    copyright: '©2025 星火电商科技有限公司',
    icpNumber: '粤ICP备12345678号-1',
    enableMultiLanguage: true,
    defaultLanguage: locale,
    supportedLanguages: ['zh-CN', 'en-US'],
    enableMultiTimezone: true,
    timezone: 'Asia/Shanghai',
    supportedTimezones: ['Asia/Shanghai', 'Asia/Tokyo', 'Europe/Berlin', 'America/Los_Angeles'],
    customerServicePhone: '400-800-1234',
    customerServiceIM: 'https://im.example.com/support',
    customerServiceEmail: 'support@example.com',
  },
  business: {
    transaction: {
      paymentChannels: {
        alipay: true,
        wechat: true,
        bank: false,
        cod: false,
      },
      withdrawalCycle: 'T+3',
      withdrawalFeeRate: 0.3,
      couponStackable: true,
    },
    product: {
      customCategories: ['智能家居-智能门锁'],
      skuGenerationRule: 'color-size',
      inventoryWarningEnabled: true,
      inventoryWarningThreshold: 5,
    },
    marketing: {
      membershipLevels: [
        { id: 'vip-silver', name: '白银会员', threshold: 1000, perks: '专属折扣95折，生日礼券' },
        { id: 'vip-gold', name: '黄金会员', threshold: 5000, perks: '专属折扣9折，提前购权益' },
      ],
      enableGroupPurchase: true,
      enablePreSale: false,
      categoryLimitedTools: [
        { category: '珠宝', feature: '拼团', enabled: true },
        { category: '美妆', feature: '买赠', enabled: true },
      ],
      promotionTemplates: [
        { id: 'full-200-30', name: '满200减30', rule: '满200减30', scope: '全平台通用' },
      ],
    },
  },
  permissions: {
    rbacEnabled: true,
    roles: [
      {
        key: 'super-admin',
        name: '超级管理员',
        description: '拥有全局配置权限',
        permissions: ['settings:*', 'marketing:*', 'finance:*', 'merchant:*'],
      },
      {
        key: 'operator',
        name: '运营',
        description: '负责营销策略和内容管理',
        permissions: ['marketing:*', 'product:view', 'order:view'],
        restrictedActions: ['payment:secret:update'],
      },
      {
        key: 'customer-service',
        name: '客服',
        description: '售前售后服务支持',
        permissions: ['order:view', 'after-sale:handle', 'customer:view'],
        restrictedActions: ['product:price:update'],
      },
      {
        key: 'merchant',
        name: '商家',
        description: '店铺级别运营者',
        permissions: ['shop:own:product', 'shop:own:order', 'shop:own:marketing'],
        restrictedActions: ['platform:settings:update', 'multi-shop:others'],
      },
      {
        key: 'finance',
        name: '财务',
        description: '负责结算与对账',
        permissions: ['finance:withdrawal', 'finance:bill', 'finance:report'],
        restrictedActions: ['marketing:config:update'],
      },
    ],
  },
  integrations: {
    oauthProviders: {
      wechat: { enabled: true, appId: '', appSecret: '', callback: 'https://example.com/auth/wechat/callback' },
      qq: { enabled: false, appId: '', appSecret: '', callback: '' },
      alipay: { enabled: false, appId: '', appSecret: '', callback: '' },
    },
    erp: { enabled: false, vendor: '旺店通', appKey: '', secret: '', callbackUrl: 'https://example.com/integration/erp' },
    wms: { enabled: true, vendor: '顺丰丰桥', appKey: '', secret: '', callbackUrl: 'https://example.com/integration/wms' },
    crm: { enabled: false, vendor: '销售易', appKey: '', secret: '', callbackUrl: 'https://example.com/integration/crm' },
    logistics: [
      { provider: '快递100', enabled: true, apiKey: '', template: '默认模板' },
      { provider: '顺丰丰桥', enabled: false, apiKey: '', template: '顺丰专用模板' },
    ],
  },
  technical: {
    caching: {
      enabled: true,
      redisTtlMinutes: 60,
      cacheWarmUp: true,
    },
    logging: {
      retentionDays: 30,
      auditRetentionDays: 90,
      sensitiveDataMasking: true,
    },
    api: {
      defaultTimeoutSeconds: 3,
      orderTimeoutSeconds: 5,
      enableCircuitBreaker: true,
    },
    backup: {
      enabled: true,
      scheduleCron: '0 2 * * *',
      offsiteEnabled: true,
      lastBackupAt: '',
    },
  },
  advanced: {
    sandboxMode: {
      enabled: true,
      guide: '沙盒用于预览系统配置变更，可邀请测试账号验证促销规则、生效范围等。',
      testers: ['tester01@example.com', 'tester02@example.com'],
    },
    multiTenant: {
      enabled: true,
      tenantRules: [
        { tenant: '旗舰店-A', enabledFeatures: ['预售', '分销'], lockedSettings: ['支付方式'] },
        { tenant: '旗舰店-B', enabledFeatures: ['拼团'], lockedSettings: ['促销模板'] },
      ],
    },
    smartRecommendations: {
      enabled: true,
      industry: '美妆',
      recommendedCombos: [
        { name: '美妆上新组合', description: '建议开启买赠 + 限时折扣，佣金设20%', applyToCategories: ['美妆', '个护'] },
        { name: '3C 促销组合', description: '建议开启预售 + 分期支付，库存阈值提升至10', applyToCategories: ['数码3C'] },
      ],
    },
    versioning: {
      autoSnapshot: true,
      versions: [
        {
          id: '2025-05-01',
          label: '五一促销版本',
          createdAt: new Date().toISOString(),
          author: '系统管理员',
          description: '启用拼团+满减，适配618预售规则',
        },
      ],
    },
  },
})

function resolveLocale(candidate: string | undefined): Language {
  return candidate === 'en-US' ? 'en-US' : 'zh-CN'
}

const defaultSettings = createDefaultSettings(resolveLocale(i18n.getLocale()))
const LEGACY_PLATFORM_NAMES = ['电商运营中台', '电商运营平台', '电商中台']

function convertLegacySettings(raw: unknown): Partial<SystemSettings> {
  if (!raw || typeof raw !== 'object') return {}
  const record = raw as Record<string, unknown>
  if ('branding' in record) {
    return raw as Partial<SystemSettings>
  }

  const legacyName = typeof record.systemName === 'string' ? record.systemName : ''
  const legacyLogo = typeof record.systemLogo === 'string' ? record.systemLogo : ''
  const legacyLang = typeof record.systemLanguage === 'string' ? record.systemLanguage : undefined
  const legacyTimezone = typeof record.systemTimezone === 'string' ? record.systemTimezone : undefined
  const legacyEmail = typeof record.smtpFrom === 'string' ? record.smtpFrom : undefined

  return {
    branding: {
      ...defaultSettings.branding,
      platformName: legacyName || defaultSettings.branding.platformName,
      platformNameZh: legacyName || defaultSettings.branding.platformNameZh,
      platformNameEn: defaultSettings.branding.platformNameEn,
      platformLogo: legacyLogo || defaultSettings.branding.platformLogo,
      defaultLanguage: resolveLocale(legacyLang),
      timezone: legacyTimezone || defaultSettings.branding.timezone,
      customerServiceEmail: legacyEmail || defaultSettings.branding.customerServiceEmail,
    },
  }
}

function normalizeSettings(value?: Partial<SystemSettings> | Record<string, unknown>): SystemSettings {
  const legacyConverted = convertLegacySettings(value)
  const merged = deepMerge(defaultSettings, legacyConverted)
  const branding = merged.branding || defaultSettings.branding
  const rawPlatformName = (branding.platformName || '').trim()
  const zhName = (branding.platformNameZh || '').trim()
  const enName = (branding.platformNameEn || '').trim()
  let fallbackName = rawPlatformName || zhName || enName || defaultSettings.branding.platformName
  if (fallbackName && LEGACY_PLATFORM_NAMES.includes(fallbackName)) {
    fallbackName = defaultSettings.branding.platformName
  }
  branding.platformName = fallbackName
  branding.platformNameZh = zhName || fallbackName
  branding.platformNameEn = enName || defaultSettings.branding.platformNameEn || fallbackName
  const allowedLanguages: Language[] = ['zh-CN', 'en-US']
  branding.supportedLanguages = Array.from(
    new Set(
      branding.supportedLanguages
        .map((lang) => resolveLocale(lang))
        .filter((lang): lang is Language => allowedLanguages.includes(lang))
    )
  )
  if (!branding.supportedLanguages.length) {
    branding.supportedLanguages = ['zh-CN', 'en-US']
  }
  branding.defaultLanguage = resolveLocale(branding.defaultLanguage)
  if (!branding.supportedLanguages.includes(branding.defaultLanguage)) {
    branding.supportedLanguages.unshift(branding.defaultLanguage)
    branding.supportedLanguages = Array.from(new Set(branding.supportedLanguages))
  }
  return merged
}

function deepMerge<T>(target: T, patch: Partial<T> | Record<string, unknown>): T {
  if (patch === undefined || patch === null) {
    return target
  }

  if (typeof target !== 'object' || target === null) {
    return patch as T
  }

  if (Array.isArray(patch)) {
    return [...patch] as unknown as T
  }

  const base: Record<string, unknown> = { ...(target as Record<string, unknown>) }

  for (const key of Object.keys(patch) as Array<keyof T>) {
    const incoming = (patch as Partial<T>)[key]
    if (incoming === undefined) continue

    if (Array.isArray(incoming)) {
      base[key as string] = [...incoming]
    } else if (typeof incoming === 'object' && incoming !== null) {
      const current = base[key as string] ?? {}
      base[key as string] = deepMerge(current as Record<string, unknown>, incoming as Record<string, unknown>)
    } else {
      base[key as string] = incoming as unknown
    }
  }

  return base as unknown as T
}

function getPlatformName(settings: Partial<SystemSettings>): string {
  const branding = (settings as Partial<SystemSettings> & { systemName?: string })?.branding
  const locale = resolveLocale(i18n.getLocale())
  const fallbackName = typeof branding?.platformName === 'string' ? branding.platformName.trim() : ''
  const zhName = typeof branding?.platformNameZh === 'string' ? branding.platformNameZh.trim() : ''
  const enName = typeof branding?.platformNameEn === 'string' ? branding.platformNameEn.trim() : ''

  const localized =
    locale === 'en-US'
      ? enName || fallbackName || zhName
      : zhName || fallbackName || enName

  if (localized) return localized

  const legacyName = typeof (settings as Record<string, unknown>)?.systemName === 'string' ? (settings as Record<string, unknown>).systemName : ''
  if (legacyName.trim()) return legacyName.trim()
  return i18n.t('settings.defaultSystemName')
}

export const useSystemSettingsStore = create<SystemSettingsState>()(
  persist(
    (set) => ({
      settings: defaultSettings,
      updateSettings: (payload) => {
        set((state) => {
          const merged = deepMerge(state.settings, payload)
          merged.branding.defaultLanguage = resolveLocale(merged.branding.defaultLanguage)
          i18n.setLocale(merged.branding.defaultLanguage)
          document.title = getPlatformName(merged)
          updateFavicon(merged.branding?.platformLogo || '')
          return { settings: merged }
        })
      },
      resetSettings: () => {
        const locale = i18n.getLocale() as Language
        const defaults = createDefaultSettings(locale)
        set({ settings: defaults })
        i18n.setLocale(defaults.branding.defaultLanguage)
        document.title = getPlatformName(defaults)
        updateFavicon('')
      },
    }),
    {
      name: 'system-settings-storage',
      onRehydrateStorage: () => (state) => {
        if (!state) return
        const normalized = normalizeSettings(state.settings)
        useSystemSettingsStore.setState({ settings: normalized })
        i18n.setLocale(normalized.branding.defaultLanguage)
        document.title = getPlatformName(normalized)
        if (normalized.branding?.platformLogo) {
          updateFavicon(normalized.branding.platformLogo)
        }
      },
    }
  )
)

function updateFavicon(logoUrl: string) {
  if (!logoUrl) {
    const link = document.querySelector("link[rel~='icon']") as HTMLLinkElement
    if (link) {
      link.href = '/vite.svg'
    }
    return
  }

  let link = document.querySelector("link[rel~='icon']") as HTMLLinkElement
  if (!link) {
    link = document.createElement('link')
    link.rel = 'icon'
    document.getElementsByTagName('head')[0].appendChild(link)
  }
  link.href = logoUrl
}

if (typeof window !== 'undefined') {
  const store = useSystemSettingsStore.getState()
  const normalized = normalizeSettings(store.settings)
  if (store.settings !== normalized) {
    useSystemSettingsStore.setState({ settings: normalized })
  }
  i18n.setLocale(normalized.branding.defaultLanguage)
  document.title = getPlatformName(normalized)
  if (normalized.branding?.platformLogo) {
    updateFavicon(normalized.branding.platformLogo)
  }
}

export type { SystemSettings as SystemSettingsType }
export default useSystemSettingsStore

